package com.kds.smarthome.controller;

import com.kds.smarthome.entity.QuartzJob;
import com.kds.smarthome.service.QuartzJobService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 孔德嵩
 * 创建日期 2025/4/18
 */
@RestController
@RequestMapping("/api/public/jobs")
public class JobController {

    private static final Logger logger = LoggerFactory.getLogger(JobController.class);

    @Autowired
    private QuartzJobService quartzJobService;

    @PostMapping("/add")
    public String addJob(@RequestBody QuartzJob quartzJob) {
        try {
            quartzJobService.addJob(quartzJob);
            return "任务添加成功";
        } catch (Exception e) {
            logger.error("任务添加失败", e);
            return "任务添加失败: " + e.getMessage();
        }
    }

    @PostMapping("/pause/{jobId}")
    public String pauseJob(@PathVariable String jobId) {
        try {
            quartzJobService.pauseJob(jobId);
            return "任务暂停成功";
        } catch (Exception e) {
            logger.error("任务暂停失败", e);
            return "任务暂停失败: " + e.getMessage();
        }
    }

    @PostMapping("/resume/{jobId}")
    public String resumeJob(@PathVariable String jobId) {
        try {
            quartzJobService.resumeJob(jobId);
            return "任务恢复成功";
        } catch (Exception e) {
            logger.error("任务恢复失败", e);
            return "任务恢复失败: " + e.getMessage();
        }
    }

    @DeleteMapping("/delete/{jobId}")
    public String deleteJob(@PathVariable String jobId) {
        try {
            quartzJobService.deleteJob(jobId);
            return "任务删除成功";
        } catch (Exception e) {
            logger.error("任务删除失败", e);
            return "任务删除失败: " + e.getMessage();
        }
    }

    @GetMapping("/detail/{jobId}")
    public QuartzJob getJobDetail(@PathVariable String jobId) {
        try {
            return quartzJobService.getJobById(jobId);
        } catch (Exception e) {
            logger.error("获取任务详情失败", e);
            return null;
        }
    }

    @GetMapping("/list")
    public List<QuartzJob> getAllJobs() {
        try {
            return quartzJobService.getAllJobs();
        } catch (Exception e) {
            logger.error("获取任务列表失败", e);
            return Collections.emptyList();
        }
    }

    @GetMapping("/running")
    public List<QuartzJob> getRunningJobs() {
        try {
            return quartzJobService.getRunningJobs();
        } catch (Exception e) {
            logger.error("获取运行中任务列表失败", e);
            return Collections.emptyList();
        }
    }

    @PostMapping("/run/{jobId}")
    public String runJobNow(@PathVariable String jobId) {
        try {
            quartzJobService.runJobNow(jobId);
            return "任务执行成功";
        } catch (Exception e) {
            logger.error("任务执行失败", e);
            return "任务执行失败: " + e.getMessage();
        }
    }

    @PostMapping("/update")
    public String updateJob(@RequestBody QuartzJob quartzJob) {
        try {
            quartzJobService.updateJob(quartzJob);
            return "更新任务成功";
        } catch (Exception e) {
            logger.error("更新任务失败", e);
            return "更新任务失败: " + e.getMessage();
        }
    }

    @PostMapping("/validate/cron")
    public Map<String, Object> validateCronExpression(@RequestParam String cronExpression) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean isValid = quartzJobService.checkCronExpression(cronExpression);
            result.put("valid", isValid);
            
            if (isValid) {
                List<String> nextExecuteTimes = quartzJobService.getNextExecuteTimeList(cronExpression, 5);
                result.put("nextExecuteTimes", nextExecuteTimes);
            }
            
            return result;
        } catch (Exception e) {
            logger.error("CRON表达式验证失败", e);
            result.put("valid", false);
            result.put("error", e.getMessage());
            return result;
        }
    }
}
